<?php
class EmailsubController extends  Controller{

    /**
     * 整体的封闭原则是对调用的client，不会有任何的影响
     */
    public function index(){
		$this->getSmarty();
		$email = isset ( $_GET ['emailAddress'] ) ?  $_GET ['emailAddress']  : null;
		$emailOrigin = isset ( $_GET ['emailOrigin'] ) ?  $_GET ['emailOrigin']  : null;
		$email = trim($email);
		
		$success = true;
		$result = "";
		$resultDetail = "";
		$sqlStr = "";
        //正常主页的情况
        if(empty($email)){

            $success = false;
            $result = "Subscribe email get more baby information";
            $resultDetail = "please input email to subscribe.at first subscibe you can get 200 points";
        }else{
            //验证邮箱的正确性
            $pattern = "/^([0-9A-Za-z\\-_\\.]+)@([0-9a-z]+\\.[a-z]{2,3}(\\.[a-z]{2})?)$/i";
            if ( preg_match( $pattern, $email ) ){
                require_once SERVICE . DS . 'EmailsService.class.php';

                $service = new EmailsService($this->getDB());
                //验证是否已经订阅
                $result = $service->getEmailsByEmail($email);
                if($result == null){
                    $service->addEmail($email,$emailOrigin);
                    $result = $service->getEmailsByEmail($email);
                    //存库提示成功
                    if($result != null){
                        $success = true;
                        $result = "Subscription success.";
                        //发送订阅邮件
                        require_once COMMON . DS . 'SendMailUtil.class.php';
                        $url = WEBSITE_URL.signup.'?p=200';
                        SendMailUtil::sendmail("Thank you subscribe babyspeedy","Dear $email:<br/> You can get 200 points by click  or access $url use browser " ,$email);

                    }else{
                        $success = false;
                        $result = "Subscription failed";
                        $resultDetail = "Sorry, please re-input email to subscribe..";
                    }
                }else{
                    $success = false;
                    $result = "Subscription failed";
                    $resultDetail = "Sorry, you fill in the email address has been subscription.";
                }


            }else{
                $success = false;
                $result = "Subscription failed";
                $resultDetail = "Sorry, you fill in the email address is invalid, please check back fill.";
            }
        }
        
        $this->smarty->assign ( 'email',$email );
		$this->smarty->assign ( 'success',$success );
		$this->smarty->assign ( 'sql',$sqlStr );
		$this->smarty->assign ( 'emailOrigin',$emailOrigin);
		$this->smarty->assign ( 'result',$result );
		$this->smarty->assign ( 'resultDetail',$resultDetail );
		$this->smarty->display("emaillist/email_subscriber.tpl");
	}


}